package chat_config

import (
	"encoding/json"
	"fmt"
	"os"
	"server_cluster/common/sharedb"
	"strconv"
	"strings"

	"gorm.io/gorm"
)

var CONF *Config = nil

type Config struct {
	SERVER_ID       int    `json:"server_id"`
	SHMKEY          int    `json:"shm_key"`
	DEV_ENV         bool   `json:"dev_env"` // 是否为开发环境
	LOG_LEVEL       string `json:"log_level"`
	GAMEHOST        string `json:"game_host"`
	DBHOST          string `json:"db_host"`
	DBPOOL          int    `json:"db_pool"`
	ConfigTablePath string `json:"config_table_path"`
}

func InitConfig() {
	if len(os.Args) > 1 && os.Args[1] == "config" {
		c := &Config{
			SERVER_ID:       4,
			SHMKEY:          1501,
			DEV_ENV:         true,
			LOG_LEVEL:       "debug",
			DBHOST:          "@tcp(192.168.3.247:3306)/jgame?charset=utf8mb4&parseTime=true&loc=Local&timeout=10s",
			DBPOOL:          1,
			ConfigTablePath: "/root/gitData/design",
		}
		c.GAMEHOST = "0.0.0.0:" + strconv.Itoa(c.SHMKEY)
		data, err := json.MarshalIndent(c, "", "\t")
		if err != nil {
			panic(err)
		}
		str := string(data)
		str = strings.ReplaceAll(str, "\\u003c", "<")
		str = strings.ReplaceAll(str, "\\u003e", ">")
		str = strings.ReplaceAll(str, "\\u0026", "&")
		err = os.WriteFile("./config.json", []byte(str), 0644)
		if err != nil {
			panic(err)
		}
		os.Exit(0)
	}

	filePath := "./config.json"
	if len(os.Args) > 1 {
		filePath = os.Args[1]
	}
	CONF = new(Config)
	CONF.loadConfigFile(filePath)
}

func (c *Config) RebuildSelf(db *gorm.DB) {
	var configServer = sharedb.Config_server{
		Id: int16(c.SERVER_ID),
	}
	err := configServer.GetOneByModel(db)
	if err != nil {
		panic(err)
	}
	c.SHMKEY = int(configServer.Port)
	c.GAMEHOST = "0.0.0.0:" + strconv.Itoa(int(configServer.Port))
	c.LOG_LEVEL = configServer.LogLevel
	c.DEV_ENV = configServer.DevEnv
	c.Write2File()
}

func (c *Config) Write2File() {
	filePath := "./config.json"
	if len(os.Args) > 1 {
		filePath = os.Args[1]
	}
	data, err := json.MarshalIndent(c, "", "\t")
	if err != nil {
		panic(err)
	}
	str := string(data)
	str = strings.ReplaceAll(str, "\\u003c", "<")
	str = strings.ReplaceAll(str, "\\u003e", ">")
	str = strings.ReplaceAll(str, "\\u0026", "&")
	err = os.WriteFile(filePath, []byte(str), 0644)
	if err != nil {
		panic(err)
	}
}

func GetConfig() *Config {
	return CONF
}

func (c *Config) loadConfigFile(filePath string) {
	data, err := os.ReadFile(filePath)
	if err != nil {
		info := fmt.Sprintf("config file load error: %v\n", err)
		panic(info)
	}
	err = json.Unmarshal(data, c)
	if err != nil {
		info := fmt.Sprintf("config file parse error: %v\n", err)
		panic(info)
	}
}
